//配置基础路径
axios.defaults.baseURL = 'http://localhost:8080'
Vue.prototype.$http = axios;

//======================axios的前置拦截器【拦截调用后端的请求====================//
axios.interceptors.request.use(res => {
    let token = localStorage.getItem("token");
    if (token) {
        res.headers["token"] = token;
    }
    return res;
}, error => {
    Promise.reject(error)
})
//======================axios的前置拦截器【拦截调用后端的请求】====================//

//======================axios的后置拦截器【处理后台登录拦截的结果】====================//
axios.interceptors.response.use(res => {
    //后端响应的是没有登录的信息
    //如果后端响应的是false和noLogin或者是timeout - 说明没有登陆信息或过期
    if (false === res.data.success && ("noLogin" === res.data.msg || "timeout" === res.data.msg)) {
        //移除localStorage中存储的token和logininfo登录信息
        localStorage.removeItem("token");
        localStorage.removeItem("logininfo");
        //跳转到登陆页面
        router.push({path: '/login'});
    }
    return res;
}, error => {
    Promise.reject(error)
})
//======================axios的后置拦截器【处理后台登录拦截的结果】====================//

//======================静态资源拦截器【处理不发axios请求就访问静态资源的请求】====================//
var path = location.href;//http://localhost/login.html / http://localhost/register.html
//如果访问的不是登录页面也不是注册页面
if (path.indexOf("/login.html") == -1 && path.indexOf("/register.html") == -1
    && path.indexOf("/binder.html") == -1 && path.indexOf("/callback.html") == -1) {
    if (!localStorage.getItem("logininfo")) {
        localStorage.removeItem("token");
        //就跳转到登陆页面
        location.href = "/login.html";
    }
}

//将地址栏上的参数转换为json对象的方法
function parseUrlParams2Obj(url) { //url=xxxxx?code=123&state=1
    //创建一个json对象 - 方便接收转换后的参数
    var obj = {};
    let params = url.substring(url.lastIndexOf("?")+1); //params - code=123&state=1 - substring含头不含尾
    for (var param of params.split("&")) { //以&分割为字符串数组并遍历 ["code=123","state=1"]
        var paramArr = param.split("=");    //再以=分割为字符串数组 ["code","123"] or ["state","1"]
        obj[paramArr[0]]=paramArr[1];   //obj对象的paramArr[0]属性的值等于paramArr[1]
    }
    return obj; //返回obj对象
}
